<template>
  <div class="myVideo">
    <video id="videoPlayer" class="video-js vjs-default-skin" controls playsinline autoplay="autoplay" width="500px">
    </video>
    <div style="display:flex;flex-direction: column;align-items: center;justify-content: center;margin-top: 20px;">
      <el-button type="primary" size="mini" @click="changeVideoUrl">切换视频源</el-button>
      <div>当前播放的是第{{currentIndex+1}}路视频</div>
    </div>
  </div>
</template>

<script>
import 'video.js/dist/video-js.css';
import videojs from 'video.js';
export default {
  name: "Videojs",
  components: {},
  data() {
    return {
      options: {
        autoplay: false, // 设置自动播放
        muted: true, // 设置了它为true，才可实现自动播放,同时视频也被静音（Chrome66及以上版本，禁止音视频的自动播放）
        preload: "auto", // 预加载
        controls: true, // 显示播放的控件
      },
      // attachmentLink: "http://192.168.99.111:9087/sms/34020000002020000001/hls/34020000001180000001_34020000001180000002/34020000001180000001_34020000001180000002_live.m3u8",
      player:null,
      videoUrls:[
        "http://192.168.99.111:9087/sms/34020000002020000001/hls/34020000001180000001_34020000001180000002/34020000001180000001_34020000001180000002_live.m3u8",
        "http://192.168.99.111:9087/sms/34020000002020000001/hls/34020000001180000001_34020000001180000007/34020000001180000001_34020000001180000007_live.m3u8",
        "http://192.168.99.111:9087/sms/34020000002020000001/hls/34020000001180000001_34020000001180000004/34020000001180000001_34020000001180000004_live.m3u8",
        "http://192.168.99.111:9087/sms/34020000002020000001/hls/34020000001180000001_34020000001180000003/34020000001180000001_34020000001180000003_live.m3u8",
      ],
      currentIndex:0,
    };
  },
  computed: {},
  created() {
  },
  mounted() {
    // 使用 $nextTick 解决vedio报错  The element or ID supplied is not valid. (videojs)
    this.$nextTick(() => {
      this.loadVideo();
    });
  },
  methods: {
    // 初始化
    loadVideo() {
      this.player = videojs("videoPlayer", this.options);
      this.play(this.videoUrls[this.currentIndex]);
    },
    // 播放视频
    play(url){
      this.player.src([
        {
          src: url,
          type: "application/x-mpegURL", // 告诉videojs,这是一个hls流
        },
      ]);
    },
    // 切换视频源
    changeVideoUrl(){
      if(this.currentIndex<3){
        this.currentIndex +=1;
      }else {
        this.currentIndex = 0;
      }
      this.play(this.videoUrls[this.currentIndex]);
    },
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose(); // dispose()会直接删除Dom元素
    }
  }
};
</script>

<style scoped lang="scss">
.video-box {
  width: 100%;
  max-width: 500px;
  max-height: 500px;
}
// 暂停播放按钮居中
::v-deep .video-js .vjs-big-play-button {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
